﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Core.Logging
{
    public sealed class TextFileLogger : LoggerBase, ILogger
    {

        public string LogFileDirectory
        {
            get
            {
                string value = System.Configuration.ConfigurationManager.AppSettings["LogFileDirectory"];
                if (value == null) { value = string.Empty; }
                return value;
            }
        }

        public string LogFileDateFormat
        {
            get
            {
                string value = System.Configuration.ConfigurationManager.AppSettings["LogFileDateFormat"];
                if (value == null) { value = "yyyyMMdd"; }
                return value;
            }
        }

        public void Log(string Source, string Title, string Message, EntryType Type)
        {
            Log(Source, Title, Message, Type, DateTime.Now, 0);
        }

        public void Log(string Source, string Title, string Message, EntryType Type, DateTime TimeStamp)
        {
            Log(Source, Title, Message, Type, TimeStamp, 0);
        }

        public void Log(string Source, string Title, string Message, EntryType Type, int EventID)
        {
            Log(Source, Title, Message, Type, DateTime.Now, EventID);
        }

        public void Log(string Source, string Title, string Message, EntryType Type, DateTime TimeStamp, int EventID)
        {
            LogEntry entry = new LogEntry();
            entry.Source = Source;
            entry.Title = Title;
            entry.Message = Message;
            entry.Type = Type;
            entry.TimeStamp = TimeStamp;
            entry.EventID = EventID;
            Log(entry);
        }

        public void Log(LogEntry Entry)
        {
            if (!IsLoggingEnabled()) { return; } 
            
            string filename = Path.Combine(LogFileDirectory, string.Format("{0}.log", DateTime.Now.ToString(this.LogFileDateFormat)));
            StreamWriter sw = null;

            if (!File.Exists(filename))
            {
                sw = File.CreateText(filename);
                sw.WriteLine("Source,Title,Message,Type,TimeStamp,EventId");
            }
            else
            {
                sw = new StreamWriter(filename, true);
            }

            sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",{3},{4},{5}", Entry.Source, Entry.Title.Replace("\n", " ").Trim(), Entry.Message.Replace("\n", " ").Trim(), Entry.Type, Entry.TimeStamp.ToString("dd-MM-yyyy HH:mm:ss"), Entry.EventID));

            sw.Flush();
            sw.Close();
        }

    }
}
